package com.example.bookkeepingelf.business.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bookkeepingelf.R;
import com.example.bookkeepingelf.base.utils.ResourceUtils;

import java.util.List;

public class SelectIconRecyclerViewAdapter extends RecyclerView.Adapter<SelectIconRecyclerViewAdapter.SelectIconViewHolder> {

    private Context context; // 上下文

    private List<String> icons;

    private LayoutInflater layoutInflater;

    private ImageView currentIcon;

    public SelectIconRecyclerViewAdapter(Context context, List<String> icons, ImageView currentIcon) {
        this.context = context;
        this.icons = icons;
        this.currentIcon = currentIcon;
        this.layoutInflater = LayoutInflater.from(context);
    }



    @NonNull
    @Override
    public SelectIconViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.item_icon, parent, false);
        return new SelectIconViewHolder(view, this);
    }

    @Override
    public void onBindViewHolder(@NonNull SelectIconViewHolder holder, int position) {
        ImageView iconImage = holder.iconImage;
        int iconResourceId = ResourceUtils.getIconResourceId(context, icons.get(position));
        iconImage.setImageResource(iconResourceId);
    }

    @Override
    public int getItemCount() {
        return icons.size();
    }


    public static class SelectIconViewHolder extends RecyclerView.ViewHolder {
        ImageView iconImage;

        public SelectIconViewHolder(@NonNull View itemView, SelectIconRecyclerViewAdapter selectIconAdapter) {
            super(itemView);
            iconImage = itemView.findViewById(R.id.icon_item_image);

            itemView.setOnClickListener(v -> {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    this.switchIcon(position, selectIconAdapter);
                }
            });
        }

        /**
         * 切换图标
         * @param position
         * @param adapter
         */
        private void switchIcon(int position, SelectIconRecyclerViewAdapter adapter) {
            String iconName = adapter.icons.get(position);
            int iconResourceId = ResourceUtils.getIconResourceId(adapter.context, iconName);
            adapter.currentIcon.setImageResource(iconResourceId);

        }
    }
}